<template>
  <div class="log-management-container">
    <h2>日志管理</h2>
    
    <!-- 日志类型切换 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabChange">
      <el-tab-pane label="操作日志" name="operation">
        <el-card shadow="hover">
          <!-- 在操作日志的filter-area中添加 -->
          <div class="filter-area">
            <el-select 
              v-model="selectedAdminId"
              placeholder="选择管理员"
              clearable
              style="width: 200px; margin-right: 10px"
            >
              <el-option
                v-for="admin in adminFilterOptions"
                :key="admin.id"
                :label="`${admin.id} - ${admin.name}`"
                :value="admin.id"
              ></el-option>
            </el-select>
            <el-input
              v-model="operationSearchQuery"
              placeholder="请输入操作内容或操作人"
              style="width: 300px; margin-right: 10px"
              @keyup.enter.native="handleOperationSearch"
            >
              <el-button slot="append" icon="el-icon-search" @click="handleOperationSearch"></el-button>
            </el-input>
            
            <el-date-picker
              v-model="operationDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 300px; margin-right: 10px"
            ></el-date-picker>
          </div>
          
          <el-table :data="filteredOperationLogs" border style="width: 100%">
            <el-table-column prop="time" label="时间" width="180"></el-table-column>
            <!-- 添加管理员ID列 -->
            <el-table-column prop="adminId" label="管理员ID" width="120"></el-table-column>
            <!-- 保留操作人列显示用户名 -->
            <el-table-column prop="adminName" label="操作人" width="120"></el-table-column>
            <el-table-column prop="module" label="模块" width="120"></el-table-column>
            <el-table-column prop="action" label="操作内容"></el-table-column>
            <el-table-column prop="ip" label="IP地址" width="150"></el-table-column>
            <el-table-column label="状态" width="100">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status === '成功' ? 'success' : 'danger'">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <!-- 删除原来的管理员列 -->
          </el-table>
          
          <el-pagination
            @size-change="handleOperationSizeChange"
            @current-change="handleOperationCurrentChange"
            :current-page="operationCurrentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="operationPageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalOperationLogs"
          ></el-pagination>
        </el-card>
      </el-tab-pane>
      
      <el-tab-pane label="异常日志" name="error">
        <el-card shadow="hover">
          <div class="filter-area">
            <el-input
              v-model="errorSearchQuery"
              placeholder="请输入错误内容"
              style="width: 300px; margin-right: 10px"
              @keyup.enter.native="handleErrorSearch"
            >
              <el-button slot="append" icon="el-icon-search" @click="handleErrorSearch"></el-button>
            </el-input>
            
            <el-select v-model="errorLevel" placeholder="错误级别" style="width: 120px; margin-right: 10px">
              <el-option label="全部" value="all"></el-option>
              <el-option label="警告" value="warning"></el-option>
              <el-option label="错误" value="error"></el-option>
              <el-option label="严重" value="critical"></el-option>
            </el-select>
          </div>
          
          <el-table :data="filteredErrorLogs" border style="width: 100%">
            <el-table-column prop="time" label="时间" width="180"></el-table-column>
            <el-table-column prop="module" label="模块" width="120"></el-table-column>
            <el-table-column prop="message" label="错误信息"></el-table-column>
            <el-table-column prop="stack" label="堆栈信息" width="120">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="showErrorDetail(scope.row)">查看详情</el-button>
              </template>
            </el-table-column>
            <el-table-column label="级别" width="100">
              <template slot-scope="scope">
                <el-tag :type="getErrorLevelTagType(scope.row.level)">
                  {{ scope.row.level }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          
          <el-pagination
            @size-change="handleErrorSizeChange"
            @current-change="handleErrorCurrentChange"
            :current-page="errorCurrentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="errorPageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalErrorLogs"
          ></el-pagination>
        </el-card>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 错误详情对话框 -->
    <el-dialog title="错误详情" :visible.sync="errorDetailVisible" width="70%">
      <div class="error-detail">
        <h3>{{ errorDetail.message }}</h3>
        <p><strong>时间：</strong>{{ errorDetail.time }}</p>
        <p><strong>模块：</strong>{{ errorDetail.module }}</p>
        <p><strong>级别：</strong>{{ errorDetail.level }}</p>
        <el-input
          type="textarea"
          :rows="10"
          readonly
          v-model="errorDetail.stack"
        ></el-input>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'LogManagement',
  // 更新data部分
  data() {
    return {
      // 移除adminRole相关字段
      adminFilterOptions: [], // 管理员筛选选项
      selectedAdminId: '',    // 选中的管理员ID
      activeTab: 'operation',
      
      // 操作日志相关数据
      operationLogs: [],
      operationSearchQuery: '',
      operationDateRange: [],
      operationCurrentPage: 1,
      operationPageSize: 10,
      
      // 异常日志相关数据
      errorLogs: [],
      errorSearchQuery: '',
      errorLevel: 'all',
      errorCurrentPage: 1,
      errorPageSize: 10,
      
      // 错误详情
      errorDetail: {},
      errorDetailVisible: false
    }
  },
  computed: {
    filteredOperationLogs() {
      return this.operationLogs.filter(log => {
        // 搜索条件
        const matchesSearch = log.action.includes(this.operationSearchQuery) || 
                          log.adminName.includes(this.operationSearchQuery)
        
        // 管理员筛选
        const matchesAdmin = !this.selectedAdminId || log.adminId === this.selectedAdminId
        
        // 操作类型筛选
        const matchesType = this.selectedOperationType === 'all' || 
                         log.operationType === this.selectedOperationType
        
        // 日期筛选
        let matchesDate = true
        if (this.operationDateRange && this.operationDateRange.length === 2) {
          const startDate = new Date(this.operationDateRange[0])
          const endDate = new Date(this.operationDateRange[1])
          const logDate = new Date(log.time)
          
          matchesDate = logDate >= startDate && logDate <= endDate
        }
        
        return matchesSearch && matchesAdmin && matchesType && matchesDate
      }).slice(
        (this.operationCurrentPage - 1) * this.operationPageSize,
        this.operationCurrentPage * this.operationPageSize
      )
    },
    totalOperationLogs() {
      return this.operationLogs.length
    },
    filteredErrorLogs() {
      return this.errorLogs.filter(log => {
        // 搜索条件
        const matchesSearch = log.message.includes(this.errorSearchQuery) || 
                          log.module.includes(this.errorSearchQuery)
        
        // 错误级别筛选
        const matchesLevel = this.errorLevel === 'all' || log.level === this.errorLevel
        
        // 错误类型筛选
        const matchesType = this.selectedErrorType === 'all' || 
                        log.errorType === this.selectedErrorType
        
        return matchesSearch && matchesLevel && matchesType
      }).slice(
        (this.errorCurrentPage - 1) * this.errorPageSize,
        this.errorCurrentPage * this.errorPageSize
      )
    },
    totalErrorLogs() {
      return this.errorLogs.length
    }
  },
  mounted() {
    this.fetchAdminList();
    this.fetchOperationLogs();
    this.fetchErrorLogs();
  },
  // 更新获取管理员列表方法
  methods: {
    fetchAdminList() {
    // 这里应该是从API获取管理员列表
    // 模拟数据
    this.adminFilterOptions = [
      {id: '1001', name: '张三'},
      {id: '1002', name: '李四'},
      {id: '1003', name: '王五'},
      // 更多管理员...
    ];
  },
    // 更新fetchOperationLogs方法
    fetchOperationLogs() {
      setTimeout(() => {
        this.operationLogs = [
          {
            time: '2023-05-15 14:30:22',
            adminId: '1001',
            adminName: '张三',
            module: '用户管理',
            action: '修改了用户信息',
            ip: '192.168.1.100',
            status: '成功'
          },
          {
            time: '2023-05-14 09:15:45',
            adminId: '1002',  // 修改为adminId
            adminName: '李四', // 修改为adminName
            module: '角色管理',
            action: '新增了编辑角色',
            ip: '120.230.110.50',
            status: '成功'
          },
          {
            time: '2023-05-13 16:20:10',
            adminId: '1003',  // 修改为adminId
            adminName: '王五', // 修改为adminName
            module: '系统设置',
            action: '自动备份数据库',
            ip: '127.0.0.1',
            status: '成功'
          },
          {
            time: '2023-05-12 11:05:33',
            adminId: '1001',  // 修改为adminId
            adminName: '张三', // 修改为adminName
            module: '内容管理',
            action: '删除了违规帖子',
            ip: '192.168.1.100',
            status: '失败'
          }
        ]
      }, 500)
    },
    fetchErrorLogs() {
      // 模拟API调用
      setTimeout(() => {
        this.errorLogs = [
          {
            time: '2023-05-15 14:30:22',
            module: '用户服务',
            message: '用户信息查询失败',
            stack: 'Error: 数据库连接超时\n    at UserService.queryUserInfo (user.service.js:45:15)',
            level: 'error'
          },
          {
            time: '2023-05-14 09:15:45',
            module: 'API网关',
            message: '检测到可疑请求',
            stack: 'Warning: 可疑IP 192.168.1.100尝试暴力破解\n    at SecurityFilter.checkRequest (security.js:78:10)',
            level: 'warning'
          },
          {
            time: '2023-05-13 16:20:10',
            module: '数据库',
            message: '数据库连接池耗尽',
            stack: 'Critical: 数据库连接池已满\n    at DBConnectionPool.getConnection (db.js:112:5)',
            level: 'critical'
          }
        ]
      }, 500)
    },
    handleTabChange(tab) {
      if (tab.name === 'operation') {
        this.fetchOperationLogs()
      } else {
        this.fetchErrorLogs()
      }
    },
    handleOperationSearch() {
      this.operationCurrentPage = 1
    },
    handleOperationSizeChange(val) {
      this.operationPageSize = val
    },
    handleOperationCurrentChange(val) {
      this.operationCurrentPage = val
    },
    handleErrorSearch() {
      this.errorCurrentPage = 1
    },
    handleErrorSizeChange(val) {
      this.errorPageSize = val
    },
    handleErrorCurrentChange(val) {
      this.errorCurrentPage = val
    },
    getErrorLevelTagType(level) {
      const typeMap = {
        'warning': 'warning',
        'error': 'danger',
        'critical': 'danger'
      }
      return typeMap[level] || ''
    },
    showErrorDetail(row) {
      this.errorDetail = row
      this.errorDetailVisible = true
    }
  }
}
</script>

<style scoped>
.log-management-container {
  padding: 20px;
}

.filter-area {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}

.error-detail {
  font-size: 14px;
}

.error-detail h3 {
  margin-bottom: 15px;
  color: #f56c6c;
}

.error-detail p {
  margin-bottom: 10px;
}
</style>